---
import DefaultLayout from '@layouts/DefaultLayout.astro'
import PageHeader from '@components/PageHeader.astro'
import { Badge, Card, Heading, Link, Pagination } from 'accessible-astro-components'
import { getCollection } from 'astro:content'
import type { GetStaticPaths, Page } from 'astro'
import type { CollectionEntry } from 'astro:content'
import { slugify } from '@/utils/slugify'

// Import images directly for optimization
import projectImage1 from '@assets/images/projects/project-image-1.png'
import projectImage2 from '@assets/images/projects/project-image-2.png'
import projectImage3 from '@assets/images/projects/project-image-3.png'
import projectImage4 from '@assets/images/projects/project-image-4.png'
import projectImage5 from '@assets/images/projects/project-image-5.png'
import projectImage6 from '@assets/images/projects/project-image-6.png'

export const getStaticPaths = (async ({ paginate }) => {
  const projects = await getCollection('projects')
  const allTags = projects.map((project) => project.data.tags).flat()
  const uniqueTagLabels = [...new Set(allTags)].sort((a, b) => a.localeCompare(b))
  const uniqueTags = uniqueTagLabels.map((label) => ({
    label,
    slug: slugify(label),
  }))

  const projectImages = [projectImage1, projectImage2, projectImage3, projectImage4, projectImage5, projectImage6]

  const projectsWithImages = projects.map((project, index) => {
    return {
      ...project,
      featuredImage: projectImages[index % projectImages.length],
    }
  })

  // Generate paginated pages for each tag
  const allPaginatedPages = []

  for (const tag of uniqueTags) {
    const filteredProjects = projectsWithImages.filter((project) =>
      project.data.tags.map((tag) => slugify(tag)).includes(tag.slug),
    )

    const paginatedPages = paginate(filteredProjects, {
      pageSize: 6,
      params: { tag: tag.slug },
      props: {
        currentTag: tag,
        uniqueTags,
      },
    })

    allPaginatedPages.push(...paginatedPages)
  }

  return allPaginatedPages
}) satisfies GetStaticPaths

interface Props {
  page: Page<CollectionEntry<'projects'> & { featuredImage: any }>
  currentTag: { label: string; slug: string }
  uniqueTags: { label: string; slug: string }[]
}

const { page, currentTag, uniqueTags } = Astro.props
---

<DefaultLayout
  title={`Portfolio - ${currentTag.label}`}
  description={`Projects filtered by ${currentTag.label} tag. Discover our work in ${currentTag.label} and related technologies.`}
>
  <PageHeader
    title={`Portfolio: ${currentTag.label}`}
    subtitle={`Showing ${page.total} project${page.total !== 1 ? 's' : ''} tagged with "${currentTag.label}". <a href="/portfolio">View all projects</a> or filter by other tags below.`}
    bgType="bordered"
    customBreadcrumbLabels={{
      [currentTag.slug]: currentTag.label,
    }}
    joinLastBreadcrumb={true}
  />
  <section class="my-12">
    <div class="container">
      <Heading level="h2" size="h5" class="mb-2">Tags</Heading>
      <div class="flex flex-wrap gap-4">
        <Link href="/portfolio">All projects</Link>
        {
          uniqueTags.map((tag: { label: string; slug: string }) => {
            const isCurrentTag = tag.slug === currentTag.slug
            return isCurrentTag ? (
              <Link href={'/portfolio/tag/' + tag.slug} disabled class="disabled">
                {tag.label}
              </Link>
            ) : (
              <Link href={'/portfolio/tag/' + tag.slug}>{tag.label}</Link>
            )
          })
        }
      </div>
      <p class="mt-8 text-sm">
        <em
          >Project {page.start + 1} through {page.end + 1} of {page.total} total projects tagged with "{
            currentTag.label
          }"</em
        >
      </p>
      <ul class="mt-3 grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
        {
          page.data.map((project) => (
            <li>
              <Card
                imageComponent={project.featuredImage}
                url={'/portfolio/' + project.id}
                title={project.data.title}
                headingLevel="h2"
                footer={'Author: ' + project.data.author}
                fullHeight={true}
              >
                <span slot="meta">
                  {project.data.tags.map((tag) => {
                    const isCurrentTag = tag === currentTag.label
                    return isCurrentTag ? <Badge class="bg-blue-600 text-white">{tag}</Badge> : <Badge>{tag}</Badge>
                  })}
                </span>
                {project.data.description}
              </Card>
            </li>
          ))
        }
      </ul>

      <!-- Pagination -->
      {
        page && page.lastPage > 1 && (
          <div class="mt-12 grid place-content-center">
            <Pagination
              firstPage={page.url.prev ? `/portfolio/tag/${currentTag.slug}` : null}
              previousPage={page.url.prev ? page.url.prev : null}
              nextPage={page.url.next ? page.url.next : null}
              lastPage={page.url.next ? `/portfolio/tag/${currentTag.slug}/${page.lastPage}` : null}
              currentPage={`${page.currentPage}`}
              totalPages={`${page.lastPage}`}
              ariaLabel={`${currentTag.label} portfolio pagination`}
            />
          </div>
        )
      }
    </div>
  </section>
</DefaultLayout>
